package net.longjin.exception;

import net.longjin.enums.ResBizCode;
import net.longjin.utils.ResResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：何志鹏
 * @date ：Created in 2020/11/12 16:06
 * @description：统一异常处理
 * @modified By：
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 系统异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResResult exceptionHandler(Exception e) {
        return ResResult.error(e.getMessage());
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResResult bizExceptionHandler(BizException e) {
        return ResResult.error(e.errorCode, e.errorMsg);
    }

    /**
     * 拦截请求参数异常 post请求 json格式参数
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> list = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        String message = list.get(0);
        return ResResult.error(ResBizCode.EMPTY_PARAMETER_ERROR.getCode(),message);
    }
}
